﻿using System;
using System.Data.Entity;
using System.Windows.Forms;
using RCSoft.Data;
using RCSoft.Core;

namespace RCSoft.Hotal.UI
{
    public partial class Form1 : Form
    {
        protected RCSoftObjectContext context;
        public Form1()
        {
            InitializeComponent();
            //context = new RCSoftObjectContext(GetTestDbName());
            //context.Database.Delete();
            //context.Database.Create();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var customer = GetTestCustomer();
            var fromDb = SaveAndLoadEntity(customer);
        }

        private Customer GetTestCustomer()
        {
            return new Customer
            {
                Username = "Jonelee@test.com",
                Password = "password",
                PasswordFormat = PasswordFormat.Clear,
                Email = "Jonelee@test.com",
                CustomerGuid = Guid.NewGuid(),
            };
        }

        protected T SaveAndLoadEntity<T>(T entity, bool disposeContext = true) where T : BaseEntity
        {
            context.Set<T>().Add(entity);
            context.SaveChanges();

            object id = entity.Id;
            if (disposeContext)
            {
                context.Dispose();
                context = new RCSoftObjectContext(GetTestDbName());
            }

            var fromDB = context.Set<T>().Find(id);
            return fromDB;
        }

        protected string GetTestDbName()
        {
            string testDbName = "Data Source=.;Initial Catalog=RCSoft;User ID=sa;Password=sa";
            return testDbName;
        }
    }
}
